package sliver.action.shop.ajax;

import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import sliver.action.shop.ajax.entry.ReturnCategory;
import sliver.entity.Category;
import sliver.service.ShopManager;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

@Scope("prototype")
@Controller("shop.ajax.queryCategoriesAction")
public class QueryCategoriesAction extends ActionSupport{

	private static final long serialVersionUID = -6020203191525276856L;
	
	private Integer shopperId;
	
	@Autowired
	private ShopManager shopManager;
	
	public QueryCategoriesAction(){
		
	}

	public Integer getShopperId() {
		return shopperId;
	}

	public void setShopperId(Integer shopperId) {
		this.shopperId = shopperId;
	}
	
	@Override
	public String execute() throws Exception {
		List<Category> categories = shopManager.obtainShopRootCategory(shopperId);
		
		List<ReturnCategory> returnCategories = new ArrayList<ReturnCategory>();
		ReturnCategory parentR = null;
		ReturnCategory childR = null;
		List<ReturnCategory> childrenR = null;
		if(categories != null && categories.size() > 0){
			for(Category root : categories){
				parentR = new ReturnCategory();
				parentR.setId(root.getId());
				parentR.setDeep(root.getDeep());
				parentR.setName(root.getName());
				
				Set<Category> children = root.getChildren();
				if(children != null && children.size() > 0){
					childrenR = new ArrayList<ReturnCategory>();
					for(Category child : children){
						childR = new ReturnCategory();
						childR.setId(child.getId());
						childR.setDeep(child.getDeep());
						childR.setName(child.getName());
						childrenR.add(childR);
					}
					parentR.setChildren(childrenR);
				}
				returnCategories.add(parentR);
			}
		}
		Gson gson = new Gson();
		System.out.println(gson.toJson(returnCategories));
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		
		Writer writer = response.getWriter();
		writer.write(gson.toJson(returnCategories));
		writer.flush();
		
		return null;
	}

}
